package com.dede.screensaverhelper.util

import android.content.Context
import android.content.pm.PackageManager
import android.provider.Settings
import com.dede.screensaverhelper.Config
import org.jetbrains.anko.doAsync

/**
 * @author hsh
 * @date 2018/2/2 15:45.
 * @doc
 */
object Utils {

    fun getScreenSaverState(context: Context): Boolean {
        return Settings.Secure.getInt(context.contentResolver, Config.SCREENSAVER_ENABLED, 0) == 1
    }

    fun setScreenSaverState(context: Context, newState: Boolean) {
        try {
            Settings.Secure.putInt(context.contentResolver, Config.SCREENSAVER_ENABLED, if (newState) 1 else 0)
        } catch (e: SecurityException) {
            e.printStackTrace()
            doAsync {
                JavaShellUtil.execCommand(
                        "settings put secure ${Config.SCREENSAVER_ENABLED} ${if (newState) 1 else 0}")
            }
        }
    }

    fun getScreenComponent(context: Context): String? {
        var components = Settings.Secure.getString(context.contentResolver, "screensaver_components") ?: ""
        if (components.isEmpty()) {
            components = Settings.Secure.getString(context.contentResolver, "screensaver_default_component") ?: ""
        }

        if (components.isNotEmpty()) {
            // com.dede.screensaverhelper/com.dede.screensaver.Screensaver
            val list = components.split("/")
            if (list.size == 2) {
                val packageName = list[0]
                try {
                    val packageInfo = context.packageManager.getPackageInfo(packageName, 0)
                    return packageInfo?.applicationInfo?.loadLabel(context.packageManager)?.toString()
                } catch (e: PackageManager.NameNotFoundException) {
                    e.printStackTrace()
                }
            }
        }
        return null
    }
}